{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "NMT in PyTorch.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "collapsed_sections": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/omarsar/pytorch_neural_machine_translation_attention/blob/master/NMT_in_PyTorch.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "metadata": {
        "id": "gau9xEXMGY8s",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# Neural Machine Translation with Attention Using PyTorch\n",
        "In this notebook we are going to perform machine translation using a deep learning based approach and attention mechanism. All the code is based on PyTorch and it was adopted from the tutorial provided on the official documentation of [TensorFlow](https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb).\n",
        "\n",
        "Specifically, we are going to train a sequence to sequence model for Spanish to English translation. If you are not familiar with sequence to sequence models, I have provided some references at the end of this tutorial to familiarize yourself with the concept. Even if you are not familiar with seq2seq models, you can still proceed with the coding exercise. I will explain tiny details that are important as we proceed. \n",
        "\n",
        "The tutorial is very brief and I encourage you to also take a look at the official TensorFlow [notebook](https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb) for more detailed explanations. The purpose of this tutorial is to understand how to convert certain code blocks into a deep learning framework like PyTorch. You will soon realize that the frameworks are very similar to some extent. The data preparation part is slightly different so I would emphasize that you spend more time analyzing this part of the code. \n",
        "\n",
        "If you have questions you can also reach out to me at ellfae@gmail.com or Twitter ([@omarsar0](https://twitter.com/omarsar0))."
      ]
    },
    {
      "metadata": {
        "id": "Z579-ISl9Zj6",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Import libraries"
      ]
    },
    {
      "metadata": {
        "id": "XRldb3db1Bg0",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 377
        },
        "outputId": "504abe37-6f7e-4046-ac4e-cc036821f1d6"
      },
      "cell_type": "code",
      "source": [
        "!pip3 install http://download.pytorch.org/whl/cu80/torch-0.4.1-cp36-cp36m-linux_x86_64.whl \n",
        "!pip3 install torchvision"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Collecting torch==0.4.1 from http://download.pytorch.org/whl/cu80/torch-0.4.1-cp36-cp36m-linux_x86_64.whl\n",
            "\u001b[?25l  Downloading http://download.pytorch.org/whl/cu80/torch-0.4.1-cp36-cp36m-linux_x86_64.whl (483.0MB)\n",
            "\u001b[K    100% |████████████████████████████████| 483.0MB 51.1MB/s \n",
            "tcmalloc: large alloc 1073750016 bytes == 0x56070000 @  0x7f1bbde7e2a4 0x594e17 0x626104 0x51190a 0x4f5277 0x510c78 0x5119bd 0x4f5277 0x4f3338 0x510fb0 0x5119bd 0x4f5277 0x4f3338 0x510fb0 0x5119bd 0x4f5277 0x4f3338 0x510fb0 0x5119bd 0x4f6070 0x510c78 0x5119bd 0x4f5277 0x4f3338 0x510fb0 0x5119bd 0x4f6070 0x4f3338 0x510fb0 0x5119bd 0x4f6070\n",
            "\u001b[?25hInstalling collected packages: torch\n",
            "Successfully installed torch-0.4.1\n",
            "Collecting torchvision\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/ca/0d/f00b2885711e08bd71242ebe7b96561e6f6d01fdb4b9dcf4d37e2e13c5e1/torchvision-0.2.1-py2.py3-none-any.whl (54kB)\n",
            "\u001b[K    100% |████████████████████████████████| 61kB 3.7MB/s \n",
            "\u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.14.6)\n",
            "Collecting pillow>=4.1.1 (from torchvision)\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/62/94/5430ebaa83f91cc7a9f687ff5238e26164a779cca2ef9903232268b0a318/Pillow-5.3.0-cp36-cp36m-manylinux1_x86_64.whl (2.0MB)\n",
            "\u001b[K    100% |████████████████████████████████| 2.0MB 10.8MB/s \n",
            "\u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.11.0)\n",
            "Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from torchvision) (0.4.1)\n",
            "Installing collected packages: pillow, torchvision\n",
            "  Found existing installation: Pillow 4.0.0\n",
            "    Uninstalling Pillow-4.0.0:\n",
            "      Successfully uninstalled Pillow-4.0.0\n",
            "Successfully installed pillow-5.3.0 torchvision-0.2.1\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "qT20LFmb3jSW",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "595c3efa-50dd-4f5a-9695-02ab51af4e61"
      },
      "cell_type": "code",
      "source": [
        "import torch\n",
        "import torch.functional as F\n",
        "import torch.nn as nn\n",
        "import torch.optim as optim\n",
        "from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n",
        "\n",
        "import pandas as pd\n",
        "from sklearn.model_selection import train_test_split\n",
        "import numpy as np\n",
        "import unicodedata\n",
        "import re\n",
        "import time\n",
        "\n",
        "print(torch.__version__)"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "0.4.1\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "NAuXJjo9NuT8",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Import Data from Google Drive\n",
        "I stored the data on my Google Drive, but you can also obtain it from [here](http://www.manythings.org/anki/) as well. "
      ]
    },
    {
      "metadata": {
        "id": "63Ox1YURzVhF",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 122
        },
        "outputId": "1fe23f41-d672-4ddf-9e4f-cabca9de294b"
      },
      "cell_type": "code",
      "source": [
        "from google.colab import drive\n",
        "drive.mount('/gdrive')"
      ],
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdocs.test%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.photos.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fpeopleapi.readonly&response_type=code\n",
            "\n",
            "Enter your authorization code:\n",
            "··········\n",
            "Mounted at /gdrive\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "JD8Qy0eC0ZtA",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "f = open('/gdrive/My Drive/DAIR RESOURCES/PyTorch/Neural Machine Translation with PyTorch/spa.txt', encoding='UTF-8').read().strip().split('\\n')  "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "0mVlB0W14b4G",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "lines = f"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "JouLb6Eo4f28",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# sample size (try with smaller sample size to reduce computation)\n",
        "num_examples = 30000 \n",
        "\n",
        "# creates lists containing each pair\n",
        "original_word_pairs = [[w for w in l.split('\\t')] for l in lines[:num_examples]]"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "as2-5vGn4jUa",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "data = pd.DataFrame(original_word_pairs, columns=[\"eng\", \"es\"])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "913VSLih4lY3",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 204
        },
        "outputId": "3e2dc267-8f7d-40a0-f4e4-42e4d6d7b09b"
      },
      "cell_type": "code",
      "source": [
        "data.head(5)"
      ],
      "execution_count": 8,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>eng</th>\n",
              "      <th>es</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>Go.</td>\n",
              "      <td>Ve.</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>Go.</td>\n",
              "      <td>Vete.</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>Go.</td>\n",
              "      <td>Vaya.</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>Go.</td>\n",
              "      <td>Váyase.</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>Hi.</td>\n",
              "      <td>Hola.</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "   eng       es\n",
              "0  Go.      Ve.\n",
              "1  Go.    Vete.\n",
              "2  Go.    Vaya.\n",
              "3  Go.  Váyase.\n",
              "4  Hi.    Hola."
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 8
        }
      ]
    },
    {
      "metadata": {
        "id": "jCUSf31E4m6t",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Converts the unicode file to ascii\n",
        "def unicode_to_ascii(s):\n",
        "    \"\"\"\n",
        "    Normalizes latin chars with accent to their canonical decomposition\n",
        "    \"\"\"\n",
        "    return ''.join(c for c in unicodedata.normalize('NFD', s)\n",
        "        if unicodedata.category(c) != 'Mn')\n",
        "\n",
        "def preprocess_sentence(w):\n",
        "    w = unicode_to_ascii(w.lower().strip())\n",
        "    \n",
        "    # creating a space between a word and the punctuation following it\n",
        "    # eg: \"he is a boy.\" => \"he is a boy .\" \n",
        "    # Reference:- https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation\n",
        "    w = re.sub(r\"([?.!,¿])\", r\" \\1 \", w)\n",
        "    w = re.sub(r'[\" \"]+', \" \", w)\n",
        "    \n",
        "    # replacing everything with space except (a-z, A-Z, \".\", \"?\", \"!\", \",\")\n",
        "    w = re.sub(r\"[^a-zA-Z?.!,¿]+\", \" \", w)\n",
        "    \n",
        "    w = w.rstrip().strip()\n",
        "    \n",
        "    # adding a start and an end token to the sentence\n",
        "    # so that the model know when to start and stop predicting.\n",
        "    w = '<start> ' + w + ' <end>'\n",
        "    return w"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "CN2pLaZkNqrv",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Data Exploration\n",
        "Let's explore the dataset a bit."
      ]
    },
    {
      "metadata": {
        "id": "QFLV4RCR4pXa",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 359
        },
        "outputId": "31a441b5-9ab1-4b1b-93c3-2f95ca51684c"
      },
      "cell_type": "code",
      "source": [
        "# Now we do the preprocessing using pandas and lambdas\n",
        "data[\"eng\"] = data.eng.apply(lambda w: preprocess_sentence(w))\n",
        "data[\"es\"] = data.es.apply(lambda w: preprocess_sentence(w))\n",
        "data.sample(10)\n"
      ],
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>eng</th>\n",
              "      <th>es</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>14479</th>\n",
              "      <td>&lt;start&gt; the cat scared me . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; el gato me espanto . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>20413</th>\n",
              "      <td>&lt;start&gt; i wanted to see you . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; queria verte . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5675</th>\n",
              "      <td>&lt;start&gt; don t help tom . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; no ayudes a tom . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>13393</th>\n",
              "      <td>&lt;start&gt; i have it at home . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; lo tengo en casa . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>13404</th>\n",
              "      <td>&lt;start&gt; i have to go home . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; tengo que ir a casa . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>18717</th>\n",
              "      <td>&lt;start&gt; where is your room ? &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; ¿ donde esta vuestra habitacion ? &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6015</th>\n",
              "      <td>&lt;start&gt; i just want it . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; lo quiero ya . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>25393</th>\n",
              "      <td>&lt;start&gt; this is so hilarious . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; esto es tan chistoso . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>25097</th>\n",
              "      <td>&lt;start&gt; the baby is crawling . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; el bebe esta gateando . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>16464</th>\n",
              "      <td>&lt;start&gt; i have a glass eye . &lt;end&gt;</td>\n",
              "      <td>&lt;start&gt; tengo un ojo de cristal . &lt;end&gt;</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "                                        eng  \\\n",
              "14479     <start> the cat scared me . <end>   \n",
              "20413   <start> i wanted to see you . <end>   \n",
              "5675         <start> don t help tom . <end>   \n",
              "13393     <start> i have it at home . <end>   \n",
              "13404     <start> i have to go home . <end>   \n",
              "18717    <start> where is your room ? <end>   \n",
              "6015         <start> i just want it . <end>   \n",
              "25393  <start> this is so hilarious . <end>   \n",
              "25097  <start> the baby is crawling . <end>   \n",
              "16464    <start> i have a glass eye . <end>   \n",
              "\n",
              "                                                    es  \n",
              "14479               <start> el gato me espanto . <end>  \n",
              "20413                     <start> queria verte . <end>  \n",
              "5675                   <start> no ayudes a tom . <end>  \n",
              "13393                 <start> lo tengo en casa . <end>  \n",
              "13404              <start> tengo que ir a casa . <end>  \n",
              "18717  <start> ¿ donde esta vuestra habitacion ? <end>  \n",
              "6015                      <start> lo quiero ya . <end>  \n",
              "25393             <start> esto es tan chistoso . <end>  \n",
              "25097            <start> el bebe esta gateando . <end>  \n",
              "16464          <start> tengo un ojo de cristal . <end>  "
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 10
        }
      ]
    },
    {
      "metadata": {
        "id": "hqM7ZncM8V9B",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Building Vocabulary Index\n",
        "The class below is useful for creating the vocabular and index mappings which will be used to convert out inputs into indexed sequences. "
      ]
    },
    {
      "metadata": {
        "id": "2rXA7-N34sok",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# This class creates a word -> index mapping (e.g,. \"dad\" -> 5) and vice-versa \n",
        "# (e.g., 5 -> \"dad\") for each language,\n",
        "class LanguageIndex():\n",
        "    def __init__(self, lang):\n",
        "        \"\"\" lang are the list of phrases from each language\"\"\"\n",
        "        self.lang = lang\n",
        "        self.word2idx = {}\n",
        "        self.idx2word = {}\n",
        "        self.vocab = set()\n",
        "        \n",
        "        self.create_index()\n",
        "        \n",
        "    def create_index(self):\n",
        "        for phrase in self.lang:\n",
        "            # update with individual tokens\n",
        "            self.vocab.update(phrase.split(' '))\n",
        "            \n",
        "        # sort the vocab\n",
        "        self.vocab = sorted(self.vocab)\n",
        "\n",
        "        # add a padding token with index 0\n",
        "        self.word2idx['<pad>'] = 0\n",
        "        \n",
        "        # word to index mapping\n",
        "        for index, word in enumerate(self.vocab):\n",
        "            self.word2idx[word] = index + 1 # +1 because of pad token\n",
        "        \n",
        "        # index to word mapping\n",
        "        for word, index in self.word2idx.items():\n",
        "            self.idx2word[index] = word        "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Fesymsn34v7z",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 187
        },
        "outputId": "43e7a6c8-8505-4dd5-a2d7-4a82efae0ab3"
      },
      "cell_type": "code",
      "source": [
        "# index language using the class above\n",
        "inp_lang = LanguageIndex(data[\"es\"].values.tolist())\n",
        "targ_lang = LanguageIndex(data[\"eng\"].values.tolist())\n",
        "# Vectorize the input and target languages\n",
        "input_tensor = [[inp_lang.word2idx[s] for s in es.split(' ')]  for es in data[\"es\"].values.tolist()]\n",
        "target_tensor = [[targ_lang.word2idx[s] for s in eng.split(' ')]  for eng in data[\"eng\"].values.tolist()]\n",
        "input_tensor[:10]"
      ],
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[[5, 9090, 3, 4],\n",
              " [5, 9204, 3, 4],\n",
              " [5, 9082, 3, 4],\n",
              " [5, 9089, 3, 4],\n",
              " [5, 4702, 3, 4],\n",
              " [5, 2299, 1, 4],\n",
              " [5, 2304, 3, 4],\n",
              " [5, 9413, 7433, 6, 4],\n",
              " [5, 4270, 1, 4],\n",
              " [5, 4881, 1, 4]]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 12
        }
      ]
    },
    {
      "metadata": {
        "id": "uPordlA-N4qR",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 187
        },
        "outputId": "b15fd270-d92c-4e85-cc83-ff9fb478780c"
      },
      "cell_type": "code",
      "source": [
        "target_tensor[:10]"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[[5, 1857, 3, 4],\n",
              " [5, 1857, 3, 4],\n",
              " [5, 1857, 3, 4],\n",
              " [5, 1857, 3, 4],\n",
              " [5, 2058, 3, 4],\n",
              " [5, 3655, 1, 4],\n",
              " [5, 3655, 3, 4],\n",
              " [5, 4815, 6, 4],\n",
              " [5, 1636, 1, 4],\n",
              " [5, 1636, 1, 4]]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 13
        }
      ]
    },
    {
      "metadata": {
        "id": "8cwX-0rt4zmN",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def max_length(tensor):\n",
        "    return max(len(t) for t in tensor)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ycYy5gq641Uy",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# calculate the max_length of input and output tensor\n",
        "max_length_inp, max_length_tar = max_length(input_tensor), max_length(target_tensor)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "q05E5IwH42_1",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def pad_sequences(x, max_len):\n",
        "    padded = np.zeros((max_len), dtype=np.int64)\n",
        "    if len(x) > max_len: padded[:] = x[:max_len]\n",
        "    else: padded[:len(x)] = x\n",
        "    return padded"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "66dJPqzV44jd",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "8e5fe7eb-f39d-4365-a9fb-63fdaeff8f34"
      },
      "cell_type": "code",
      "source": [
        "# inplace padding\n",
        "input_tensor = [pad_sequences(x, max_length_inp) for x in input_tensor]\n",
        "target_tensor = [pad_sequences(x, max_length_tar) for x in target_tensor]\n",
        "len(target_tensor)"
      ],
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "30000"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 17
        }
      ]
    },
    {
      "metadata": {
        "id": "zvatfCWS46T-",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "2eeff7ec-2c61-4e8e-d084-ed14251a3bca"
      },
      "cell_type": "code",
      "source": [
        "# Creating training and validation sets using an 80-20 split\n",
        "input_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)\n",
        "\n",
        "# Show length\n",
        "len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val)"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(24000, 24000, 6000, 6000)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 18
        }
      ]
    },
    {
      "metadata": {
        "id": "HNFO3obpOsoB",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Load data into DataLoader for Batching\n",
        "This is just preparing the dataset so that it can be efficiently fed into the model through batches."
      ]
    },
    {
      "metadata": {
        "id": "-QRQKwxf479Q",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "from torch.utils.data import Dataset, DataLoader"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "IDSxA4OM5Qlp",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# conver the data to tensors and pass to the Dataloader \n",
        "# to create an batch iterator\n",
        "\n",
        "class MyData(Dataset):\n",
        "    def __init__(self, X, y):\n",
        "        self.data = X\n",
        "        self.target = y\n",
        "        # TODO: convert this into torch code is possible\n",
        "        self.length = [ np.sum(1 - np.equal(x, 0)) for x in X]\n",
        "        \n",
        "    def __getitem__(self, index):\n",
        "        x = self.data[index]\n",
        "        y = self.target[index]\n",
        "        x_len = self.length[index]\n",
        "        return x,y,x_len\n",
        "    \n",
        "    def __len__(self):\n",
        "        return len(self.data)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "D2WukeVF8NVn",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Parameters\n",
        "Let's define the hyperparameters and other things we need for training our NMT model."
      ]
    },
    {
      "metadata": {
        "id": "s3Be7lOZ5R-d",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "BUFFER_SIZE = len(input_tensor_train)\n",
        "BATCH_SIZE = 64\n",
        "N_BATCH = BUFFER_SIZE//BATCH_SIZE\n",
        "embedding_dim = 256\n",
        "units = 1024\n",
        "vocab_inp_size = len(inp_lang.word2idx)\n",
        "vocab_tar_size = len(targ_lang.word2idx)\n",
        "\n",
        "train_dataset = MyData(input_tensor_train, target_tensor_train)\n",
        "val_dataset = MyData(input_tensor_val, target_tensor_val)\n",
        "\n",
        "dataset = DataLoader(train_dataset, batch_size = BATCH_SIZE, \n",
        "                     drop_last=True,\n",
        "                     shuffle=True)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "blYXo7pv5TOu",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "class Encoder(nn.Module):\n",
        "    def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):\n",
        "        super(Encoder, self).__init__()\n",
        "        self.batch_sz = batch_sz\n",
        "        self.enc_units = enc_units\n",
        "        self.vocab_size = vocab_size\n",
        "        self.embedding_dim = embedding_dim\n",
        "        self.embedding = nn.Embedding(self.vocab_size, self.embedding_dim)\n",
        "        self.gru = nn.GRU(self.embedding_dim, self.enc_units)\n",
        "        \n",
        "    def forward(self, x, lens, device):\n",
        "        # x: batch_size, max_length \n",
        "        \n",
        "        # x: batch_size, max_length, embedding_dim\n",
        "        x = self.embedding(x) \n",
        "                \n",
        "        # x transformed = max_len X batch_size X embedding_dim\n",
        "        # x = x.permute(1,0,2)\n",
        "        x = pack_padded_sequence(x, lens) # unpad\n",
        "    \n",
        "        self.hidden = self.initialize_hidden_state(device)\n",
        "        \n",
        "        # output: max_length, batch_size, enc_units\n",
        "        # self.hidden: 1, batch_size, enc_units\n",
        "        output, self.hidden = self.gru(x, self.hidden) # gru returns hidden state of all timesteps as well as hidden state at last timestep\n",
        "        \n",
        "        # pad the sequence to the max length in the batch\n",
        "        output, _ = pad_packed_sequence(output)\n",
        "        \n",
        "        return output, self.hidden\n",
        "\n",
        "    def initialize_hidden_state(self, device):\n",
        "        return torch.zeros((1, self.batch_sz, self.enc_units)).to(device)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "SrsQ7dTg5V__",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "### sort batch function to be able to use with pad_packed_sequence\n",
        "def sort_batch(X, y, lengths):\n",
        "    lengths, indx = lengths.sort(dim=0, descending=True)\n",
        "    X = X[indx]\n",
        "    y = y[indx]\n",
        "    return X.transpose(0,1), y, lengths # transpose (batch x seq) to (seq x batch)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "2X1h155CPQ1Y",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Testing the Encoder\n",
        "Before proceeding with training, we should always try to test out model behavior such as the size of outputs just to make that things are going as expected. In PyTorch this can be done easily since everything comes in eager execution by default."
      ]
    },
    {
      "metadata": {
        "id": "rbSLACY45Xz-",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "d6461fcf-eba8-4843-f2d2-e5d77e788696"
      },
      "cell_type": "code",
      "source": [
        "### Testing Encoder part\n",
        "# TODO: put whether GPU is available or not\n",
        "# Device\n",
        "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
        "encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n",
        "\n",
        "encoder.to(device)\n",
        "# obtain one sample from the data iterator\n",
        "it = iter(dataset)\n",
        "x, y, x_len = next(it)\n",
        "\n",
        "# sort the batch first to be able to use with pac_pack_sequence\n",
        "xs, ys, lens = sort_batch(x, y, x_len)\n",
        "\n",
        "enc_output, enc_hidden = encoder(xs.to(device), lens, device)\n",
        "\n",
        "print(enc_output.size()) # max_length, batch_size, enc_units"
      ],
      "execution_count": 24,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "torch.Size([12, 64, 1024])\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "t4djvgil5bMQ",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "class Decoder(nn.Module):\n",
        "    def __init__(self, vocab_size, embedding_dim, dec_units, enc_units, batch_sz):\n",
        "        super(Decoder, self).__init__()\n",
        "        self.batch_sz = batch_sz\n",
        "        self.dec_units = dec_units\n",
        "        self.enc_units = enc_units\n",
        "        self.vocab_size = vocab_size\n",
        "        self.embedding_dim = embedding_dim\n",
        "        self.embedding = nn.Embedding(self.vocab_size, self.embedding_dim)\n",
        "        self.gru = nn.GRU(self.embedding_dim + self.enc_units, \n",
        "                          self.dec_units,\n",
        "                          batch_first=True)\n",
        "        self.fc = nn.Linear(self.enc_units, self.vocab_size)\n",
        "        \n",
        "        # used for attention\n",
        "        self.W1 = nn.Linear(self.enc_units, self.dec_units)\n",
        "        self.W2 = nn.Linear(self.enc_units, self.dec_units)\n",
        "        self.V = nn.Linear(self.enc_units, 1)\n",
        "    \n",
        "    def forward(self, x, hidden, enc_output):\n",
        "        # enc_output original: (max_length, batch_size, enc_units)\n",
        "        # enc_output converted == (batch_size, max_length, hidden_size)\n",
        "        enc_output = enc_output.permute(1,0,2)\n",
        "        # hidden shape == (batch_size, hidden size)\n",
        "        # hidden_with_time_axis shape == (batch_size, 1, hidden size)\n",
        "        # we are doing this to perform addition to calculate the score\n",
        "        \n",
        "        # hidden shape == (batch_size, hidden size)\n",
        "        # hidden_with_time_axis shape == (batch_size, 1, hidden size)\n",
        "        hidden_with_time_axis = hidden.permute(1, 0, 2)\n",
        "        \n",
        "        # score: (batch_size, max_length, hidden_size)\n",
        "        score = torch.tanh(self.W1(enc_output) + self.W2(hidden_with_time_axis))\n",
        "        \n",
        "        #score = torch.tanh(self.W2(hidden_with_time_axis) + self.W1(enc_output))\n",
        "          \n",
        "        # attention_weights shape == (batch_size, max_length, 1)\n",
        "        # we get 1 at the last axis because we are applying score to self.V\n",
        "        attention_weights = torch.softmax(self.V(score), dim=1)\n",
        "        \n",
        "        # context_vector shape after sum == (batch_size, hidden_size)\n",
        "        context_vector = attention_weights * enc_output\n",
        "        context_vector = torch.sum(context_vector, dim=1)\n",
        "        \n",
        "        # x shape after passing through embedding == (batch_size, 1, embedding_dim)\n",
        "        x = self.embedding(x)\n",
        "        \n",
        "        # x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)\n",
        "        #x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)\n",
        "        # ? Looks like attention vector in diagram of source\n",
        "        x = torch.cat((context_vector.unsqueeze(1), x), -1)\n",
        "        \n",
        "        # passing the concatenated vector to the GRU\n",
        "        # output: (batch_size, 1, hidden_size)\n",
        "        output, state = self.gru(x)\n",
        "        \n",
        "        \n",
        "        # output shape == (batch_size * 1, hidden_size)\n",
        "        output =  output.view(-1, output.size(2))\n",
        "        \n",
        "        # output shape == (batch_size * 1, vocab)\n",
        "        x = self.fc(output)\n",
        "        \n",
        "        return x, state, attention_weights\n",
        "    \n",
        "    def initialize_hidden_state(self):\n",
        "        return torch.zeros((1, self.batch_sz, self.dec_units))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "HsG5We7Sk_UR",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Testing the Decoder\n",
        "Similarily, try to test the decoder."
      ]
    },
    {
      "metadata": {
        "id": "lmipPRVx5fqO",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 170
        },
        "outputId": "d9c4cbf1-02b9-4be1-8f6f-340a42bd38ef"
      },
      "cell_type": "code",
      "source": [
        "# Device\n",
        "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
        "encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n",
        "\n",
        "encoder.to(device)\n",
        "# obtain one sample from the data iterator\n",
        "it = iter(dataset)\n",
        "x, y, x_len = next(it)\n",
        "\n",
        "print(\"Input: \", x.shape)\n",
        "print(\"Output: \", y.shape)\n",
        "\n",
        "# sort the batch first to be able to use with pac_pack_sequence\n",
        "xs, ys, lens = sort_batch(x, y, x_len)\n",
        "\n",
        "enc_output, enc_hidden = encoder(xs.to(device), lens, device)\n",
        "print(\"Encoder Output: \", enc_output.shape) # batch_size X max_length X enc_units\n",
        "print(\"Encoder Hidden: \", enc_hidden.shape) # batch_size X enc_units (corresponds to the last state)\n",
        "\n",
        "decoder = Decoder(vocab_tar_size, embedding_dim, units, units, BATCH_SIZE)\n",
        "decoder = decoder.to(device)\n",
        "\n",
        "#print(enc_hidden.squeeze(0).shape)\n",
        "\n",
        "dec_hidden = enc_hidden#.squeeze(0)\n",
        "dec_input = torch.tensor([[targ_lang.word2idx['<start>']]] * BATCH_SIZE)\n",
        "print(\"Decoder Input: \", dec_input.shape)\n",
        "print(\"--------\")\n",
        "\n",
        "for t in range(1, y.size(1)):\n",
        "    # enc_hidden: 1, batch_size, enc_units\n",
        "    # output: max_length, batch_size, enc_units\n",
        "    predictions, dec_hidden, _ = decoder(dec_input.to(device), \n",
        "                                         dec_hidden.to(device), \n",
        "                                         enc_output.to(device))\n",
        "    \n",
        "    print(\"Prediction: \", predictions.shape)\n",
        "    print(\"Decoder Hidden: \", dec_hidden.shape)\n",
        "    \n",
        "    #loss += loss_function(y[:, t].to(device), predictions.to(device))\n",
        "    \n",
        "    dec_input = y[:, t].unsqueeze(1)\n",
        "    print(dec_input.shape)\n",
        "    break"
      ],
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Input:  torch.Size([64, 16])\n",
            "Output:  torch.Size([64, 11])\n",
            "Encoder Output:  torch.Size([11, 64, 1024])\n",
            "Encoder Hidden:  torch.Size([1, 64, 1024])\n",
            "Decoder Input:  torch.Size([64, 1])\n",
            "--------\n",
            "Prediction:  torch.Size([64, 4935])\n",
            "Decoder Hidden:  torch.Size([1, 64, 1024])\n",
            "torch.Size([64, 1])\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "QclyWIop5dRG",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "criterion = nn.CrossEntropyLoss()\n",
        "\n",
        "def loss_function(real, pred):\n",
        "    \"\"\" Only consider non-zero inputs in the loss; mask needed \"\"\"\n",
        "    #mask = 1 - np.equal(real, 0) # assign 0 to all above 0 and 1 to all 0s\n",
        "    #print(mask)\n",
        "    mask = real.ge(1).type(torch.cuda.FloatTensor)\n",
        "    \n",
        "    loss_ = criterion(pred, real) * mask \n",
        "    return torch.mean(loss_)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "LjMMYJv85hVT",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Device\n",
        "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
        "\n",
        "## TODO: Combine the encoder and decoder into one class\n",
        "encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n",
        "decoder = Decoder(vocab_tar_size, embedding_dim, units, units, BATCH_SIZE)\n",
        "\n",
        "encoder.to(device)\n",
        "decoder.to(device)\n",
        "\n",
        "optimizer = optim.Adam(list(encoder.parameters()) + list(decoder.parameters()), \n",
        "                       lr=0.001)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "x6_WoDZM7reU",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Training\n",
        "Now we start the training. We are only using 10 epochs but you can expand this to keep trainining the model for a longer period of time. Note that in this case we are teacher forcing during training. Find a more detailed explanation in the official TensorFlow [implementation](https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb) of this notebook provided by the TensorFlow team. "
      ]
    },
    {
      "metadata": {
        "id": "KN8G-3YY8ADm",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1207
        },
        "outputId": "52c3acf4-10be-48c5-b305-4c6d24627517"
      },
      "cell_type": "code",
      "source": [
        "EPOCHS = 10\n",
        "\n",
        "for epoch in range(EPOCHS):\n",
        "    start = time.time()\n",
        "    \n",
        "    encoder.train()\n",
        "    decoder.train()\n",
        "    \n",
        "    total_loss = 0\n",
        "    \n",
        "    for (batch, (inp, targ, inp_len)) in enumerate(dataset):\n",
        "        loss = 0\n",
        "        \n",
        "        xs, ys, lens = sort_batch(inp, targ, inp_len)\n",
        "        enc_output, enc_hidden = encoder(xs.to(device), lens, device)\n",
        "        dec_hidden = enc_hidden\n",
        "        dec_input = torch.tensor([[targ_lang.word2idx['<start>']]] * BATCH_SIZE)\n",
        "        \n",
        "        for t in range(1, ys.size(1)):\n",
        "            predictions, dec_hidden, _ = decoder(dec_input.to(device), \n",
        "                                         dec_hidden.to(device), \n",
        "                                         enc_output.to(device))\n",
        "            loss += loss_function(ys[:, t].to(device), predictions.to(device))\n",
        "            #loss += loss_\n",
        "            dec_input = ys[:, t].unsqueeze(1)\n",
        "            \n",
        "        \n",
        "        batch_loss = (loss / int(ys.size(1)))\n",
        "        total_loss += batch_loss\n",
        "        \n",
        "        optimizer.zero_grad()\n",
        "        \n",
        "        loss.backward()\n",
        "\n",
        "        ### UPDATE MODEL PARAMETERS\n",
        "        optimizer.step()\n",
        "        \n",
        "        if batch % 100 == 0:\n",
        "            print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1,\n",
        "                                                         batch,\n",
        "                                                         batch_loss.detach().item()))\n",
        "        \n",
        "        \n",
        "    ### TODO: Save checkpoint for model\n",
        "    print('Epoch {} Loss {:.4f}'.format(epoch + 1,\n",
        "                                        total_loss / N_BATCH))\n",
        "    print('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))\n",
        "    \n",
        "    \n",
        "    \n",
        "    "
      ],
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Epoch 1 Batch 0 Loss 4.6125\n",
            "Epoch 1 Batch 100 Loss 1.6659\n",
            "Epoch 1 Batch 200 Loss 1.1911\n",
            "Epoch 1 Batch 300 Loss 1.1147\n",
            "Epoch 1 Loss 1.4692\n",
            "Time taken for 1 epoch 51.93851661682129 sec\n",
            "\n",
            "Epoch 2 Batch 0 Loss 0.8044\n",
            "Epoch 2 Batch 100 Loss 0.6910\n",
            "Epoch 2 Batch 200 Loss 0.7195\n",
            "Epoch 2 Batch 300 Loss 0.6796\n",
            "Epoch 2 Loss 0.7119\n",
            "Time taken for 1 epoch 52.01424741744995 sec\n",
            "\n",
            "Epoch 3 Batch 0 Loss 0.3663\n",
            "Epoch 3 Batch 100 Loss 0.3461\n",
            "Epoch 3 Batch 200 Loss 0.4014\n",
            "Epoch 3 Batch 300 Loss 0.3965\n",
            "Epoch 3 Loss 0.3881\n",
            "Time taken for 1 epoch 52.2163941860199 sec\n",
            "\n",
            "Epoch 4 Batch 0 Loss 0.2015\n",
            "Epoch 4 Batch 100 Loss 0.2091\n",
            "Epoch 4 Batch 200 Loss 0.2374\n",
            "Epoch 4 Batch 300 Loss 0.2498\n",
            "Epoch 4 Loss 0.2204\n",
            "Time taken for 1 epoch 52.22896146774292 sec\n",
            "\n",
            "Epoch 5 Batch 0 Loss 0.1061\n",
            "Epoch 5 Batch 100 Loss 0.1226\n",
            "Epoch 5 Batch 200 Loss 0.1127\n",
            "Epoch 5 Batch 300 Loss 0.1286\n",
            "Epoch 5 Loss 0.1395\n",
            "Time taken for 1 epoch 52.19645810127258 sec\n",
            "\n",
            "Epoch 6 Batch 0 Loss 0.1089\n",
            "Epoch 6 Batch 100 Loss 0.1074\n",
            "Epoch 6 Batch 200 Loss 0.1066\n",
            "Epoch 6 Batch 300 Loss 0.1371\n",
            "Epoch 6 Loss 0.1025\n",
            "Time taken for 1 epoch 52.23947715759277 sec\n",
            "\n",
            "Epoch 7 Batch 0 Loss 0.0439\n",
            "Epoch 7 Batch 100 Loss 0.0801\n",
            "Epoch 7 Batch 200 Loss 0.0868\n",
            "Epoch 7 Batch 300 Loss 0.0746\n",
            "Epoch 7 Loss 0.0832\n",
            "Time taken for 1 epoch 52.218220233917236 sec\n",
            "\n",
            "Epoch 8 Batch 0 Loss 0.0718\n",
            "Epoch 8 Batch 100 Loss 0.0752\n",
            "Epoch 8 Batch 200 Loss 0.0482\n",
            "Epoch 8 Batch 300 Loss 0.1020\n",
            "Epoch 8 Loss 0.0712\n",
            "Time taken for 1 epoch 52.18943977355957 sec\n",
            "\n",
            "Epoch 9 Batch 0 Loss 0.0623\n",
            "Epoch 9 Batch 100 Loss 0.0690\n",
            "Epoch 9 Batch 200 Loss 0.0778\n",
            "Epoch 9 Batch 300 Loss 0.0705\n",
            "Epoch 9 Loss 0.0650\n",
            "Time taken for 1 epoch 52.27435898780823 sec\n",
            "\n",
            "Epoch 10 Batch 0 Loss 0.0552\n",
            "Epoch 10 Batch 100 Loss 0.0621\n",
            "Epoch 10 Batch 200 Loss 0.0684\n",
            "Epoch 10 Batch 300 Loss 0.0439\n",
            "Epoch 10 Loss 0.0635\n",
            "Time taken for 1 epoch 52.313509464263916 sec\n",
            "\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "_tF5jMP0-cmv",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Final Words\n",
        "Notice that we only trained the model and that's it. In fact, this notebook is in experimental phase, so there could also be some bugs or something I missed during the process of converting code or training. Please comment your concerns here or submit it as an issue in the GitHub version of this notebook. I will appreciate it!\n",
        "\n",
        "We didn't evaluate the model or analyzed it. To encourage you to practice what you have learned in the notebook, I will suggest that you try to convert the TensorFlow code used in the [original notebook](https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb) and complete this notebook. I believe the code should be straightforward, the hard part was already done in this notebook. If you manage to complete it, please submit a PR on the GitHub version of this notebook. I will gladly accept your PR. Thanks for reading and hope this notebook was useful. Keep tuned for notebooks like this on my Twitter ([omarsar0](https://twitter.com/omarsar0)). "
      ]
    },
    {
      "metadata": {
        "id": "cl4ZgMd-KyTU",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## References\n",
        "\n",
        "### Seq2Seq:\n",
        "  - Sutskever et al. (2014) - [Sequence to Sequence Learning with Neural Networks](Sequence to Sequence Learning with Neural Networks)\n",
        "  - [Sequence to sequence model: Introduction and concepts](https://towardsdatascience.com/sequence-to-sequence-model-introduction-and-concepts-44d9b41cd42d)\n",
        "  - [Blog on seq2seq](https://guillaumegenthial.github.io/sequence-to-sequence.html)\n",
        "  - [Bahdanau et al. (2016) NMT jointly learning to align and translate](https://arxiv.org/pdf/1409.0473.pdf)\n",
        "  - [Attention is all you need](https://arxiv.org/pdf/1706.03762.pdf)"
      ]
    }
  ]
}